from rest_framework import generics
from rest_framework.response import Response

from amat_app.adb_helper.adb_device_models import AdbDeviceModel
from amat_app.adb_helper.adb_devices_serializers import AdbDeviceSerializer
from amat_app.adb_helper.adb_helper import ADBHelper


def get_device_detail(udid) -> dict:
    __imei = ADBHelper(udid).get_device_imei()
    __wifi = ADBHelper(udid).get_device_ip_address()
    __status = ADBHelper(udid).get_status()[0]
    if __status == "device":
        __status = "online"
    if not __imei:
        __imei = ""
    if not __wifi:
        __wifi = ""
    if not __status:
        __status = ""
    return {
        "udid": udid,
        "status": __status,
        "name": udid,
        "imei": __imei,
    }


class AdbConnectedDevicesListView(generics.ListCreateAPIView):
    serializer_class = AdbDeviceSerializer

    def get(self, request, *args, **kwargs):
        dev = ADBHelper().devices()

        _results = []
        for udid, status in dev:

            if status == "device":
                __satus = "online"
                __imei = ADBHelper(udid).get_device_imei()
            else:
                __satus = "offline"
                __imei = ""
            __dev_info = {
                "udid": udid,
                "status": __satus,
                "name": udid,
                "imei": __imei,
            }
            __device = AdbDeviceModel(
                **__dev_info
            )

            _results.append(__dev_info)
        print(_results)
        return Response(_results)


class ConnectDeviceView(generics.CreateAPIView):

    def post(self, request, *args, **kw):
        device_ip = request.query_params.get("ip")

        def connect_(ip):
            for i in range(2):
                _all = ADBHelper().devices(state='device')
                for __udid, state in _all:
                    if __udid == ip:
                        return True
                    else:
                        # 未找到设备，尝试连接
                        _c = ADBHelper(ip).connect()
            else:
                return False

        print("==========================")
        dev = connect_(device_ip)
        _dev = {}
        if dev:
            _dev["status"] = True
            _dev["msg"] = "连接设备成功"
            _dev["details"] = get_device_detail(device_ip)
        else:
            _dev["status"] = False
            _dev["msg"] = "连接设备失败"
            _dev["details"] = {}
        print(f"_dev: {_dev}")
        return Response(_dev)
